//
//  KuangjiViewController.m
//  gpos_app
//
//  Created by apple on 2018/8/19.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "KuangjiViewController.h"
#import "Masonry.h"
#import "juangjiViewCell.h"
#import "kjDetailsViewController.h"
#import "ITDatePickerController.h"
#import "GPosAPI.h"
#import "SVProgressHUD.h"
#import "homeModel.h"
#import "XMRegisterViewController.h"
#import "MJRefresh.h"
@interface KuangjiViewController ()<UITableViewDelegate,UITableViewDataSource,ITDatePickerControllerDelegate>
@property (nonatomic,strong)UITableView * tableView;
@property (nonatomic,strong)UIView * topView;
@property (nonatomic,strong)UILabel * TimeLabel;
@property (nonatomic,strong)NSString * timeStr;
@property (strong, nonatomic) NSDate *startDate;
@property (nonatomic,assign) int page;
@property (nonatomic,strong)NSMutableArray * modelArr;
@property (nonatomic,strong)UIView * qstView;

@end

@implementation KuangjiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:244/255.0f green:244/255.0f blue:244/255.0f alpha:1];
    NSDate *date = [NSDate date];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM"];
    NSString *DateTime = [formatter stringFromDate:date];
    self.timeStr = DateTime;
    [self LoadData];
    
}

- (void)LoadData{
    self.page = 1;
    __weak typeof(self) weakSelf = self;
     weakSelf.modelArr = [[NSMutableArray alloc] init];
    int user = [[[NSUserDefaults standardUserDefaults] objectForKey:@"userId"] intValue];
    NSString * str = [weakSelf.timeStr stringByReplacingOccurrencesOfString:@"-"withString:@""];
    NSDictionary * params = @{@"startTime" : @([str intValue]),
                              @"pageSize" : @(10),
                              @"userId" : @(user),
                              @"page" : @(self.page)
                              };
    NSLog(@"oj---%@",params);
    [GPosAPI requestGetUserMinerDetailListWithParams:params andCallback:^(id obj) {
        NSLog(@"obj---%@",obj);
        if ( obj == nil ){
            
            [SVProgressHUD showInfoWithStatus:@"请求失败"];
            [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
            [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
        }else {
    
           
            if ([[obj objectForKey:@"code"] intValue] == 200) {
                NSArray * arr = [[NSArray alloc] init];
                arr = [obj objectForKey:@"data"];
                for (NSDictionary * dic in arr) {
                    homeModel *model = [[homeModel alloc] init];
                    model.jia = [dic objectForKey:@"jia"];
                    model.tid = [dic objectForKey:@"id"];
                    model.time = [dic objectForKey:@"time"];
                    [weakSelf.modelArr addObject:model];
                }
                [weakSelf.tableView reloadData];
                NSLog(@"self---%@",[obj objectForKey:@"data"]);
               
            }else if ([[obj objectForKey:@"code"] intValue] == 401 || [[obj objectForKey:@"code"] intValue] == 402) {
                
                UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"passWord"];
                //storyboard里的ID
                XMRegisterViewController *vc = [mainStory instantiateInitialViewController];
                vc.navigationController.navigationBarHidden=NO;
                //                    //设置当前窗口的根控制器
                
                [UIApplication sharedApplication].keyWindow.rootViewController=vc;
                [SVProgressHUD showInfoWithStatus:[obj objectForKey:@"message"]];
                [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
            }else {
                [SVProgressHUD showErrorWithStatus:[obj objectForKey:@"message"]];
                [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
                
            }
        }
        [weakSelf topLoadView];
        [weakSelf bottomLoadView];
    }];
    
    
}

- (void)bottomLoadView {
    self.tableView = [[UITableView alloc] init];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.mj_footer=[MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreShopss)];
    [self.view addSubview:self.tableView];
    
    UIView * footerView = [[UIView alloc] init];
    footerView.backgroundColor = [UIColor colorWithRed:244/255.0f green:244/255.0f blue:244/255.0f alpha:1];
    self.tableView.tableFooterView = footerView;
    if (iPhoneX) {
        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.topView.mas_bottom).with.offset(0);
            make.left.equalTo(self.view).with.offset(0);
            make.right.equalTo(self.view).with.offset(0);
            make.bottom.equalTo(self.view).with.offset(-kBottomSafeHeight);
            
        }];
    }else {
        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.topView.mas_bottom).with.offset(0);
            make.left.equalTo(self.view).with.offset(0);
            make.right.equalTo(self.view).with.offset(0);
            make.bottom.equalTo(self.view).with.offset(-10);
            
        }];
        
    }
    self.qstView = [[UIView alloc] init];
    self.qstView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.qstView];
    if (iPhoneX) {
        [self.qstView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.topView.mas_bottom).with.offset(0);
            make.left.equalTo(self.view).with.offset(0);
            make.right.equalTo(self.view).with.offset(0);
            make.bottom.equalTo(self.view).with.offset(-kBottomSafeHeight);
            
        }];
    }else {
        [self.qstView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.topView.mas_bottom).with.offset(0);
            make.left.equalTo(self.view).with.offset(0);
            make.right.equalTo(self.view).with.offset(0);
            make.bottom.equalTo(self.view).with.offset(-10);
            
        }];
        
    }
    self.qstView.hidden = YES;
    UIImageView * qstImage = [[UIImageView alloc] init];
    qstImage.image = [UIImage imageNamed:@"icon_zwmingxi"];
    [self.qstView addSubview:qstImage];
    [qstImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.qstView);//
        make.top.equalTo(self.qstView).with.offset(KmainScreenHeiht/4);
    }];
    UILabel * qstLabel = [[UILabel alloc] init];
    qstLabel.text = @"暂无明细";
    qstLabel.textColor = [UIColor grayColor];
    qstLabel.font = [UIFont systemFontOfSize:13.f];
    [self.qstView addSubview:qstLabel];
    [qstLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(qstImage.mas_bottom).with.offset(5);
        make.centerX.equalTo(qstImage);
    }];
    
    if (self.modelArr.count == 0) {
        self.tableView.hidden = YES;
        self.qstView.hidden = NO;
    }else {
        self.tableView.hidden = NO;
        self.qstView.hidden = YES;
        
    }

}
- (void)topLoadView {
    self.topView = [[UIView alloc] init];
    self.topView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.topView];
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(0);
        make.left.equalTo(self.view).with.offset(0);
        make.right.equalTo(self.view).with.offset(0);
        make.height.equalTo(@30);
    }];
    
    UIButton * timeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [timeButton setImage:[UIImage imageNamed:@"icon_rili"] forState:UIControlStateNormal];
    [timeButton addTarget:self action:@selector(timeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.topView addSubview:timeButton];
    [timeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.topView);
        make.right.equalTo(self.topView).with.offset(-16);
    }];
    
    self.TimeLabel = [[UILabel alloc] init];
    self.TimeLabel.font = [UIFont systemFontOfSize:14];
    self.TimeLabel.textColor = [UIColor grayColor];
    [self.topView addSubview:self.TimeLabel];
    [self.TimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.topView);
        make.left.equalTo(self.topView).with.offset(16);
        
    }];
    
    self.TimeLabel.text = [NSString stringWithFormat:@"%@(单位:GPOS)",self.timeStr];
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.modelArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{//rankingCell
    
    juangjiViewCell * cell = [[juangjiViewCell alloc] init];
    cell = [tableView dequeueReusableCellWithIdentifier:@"kuangjiCell"];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"juangjiViewCell" owner:self options:nil] firstObject];
    }
    cell.touxiangImage.image = [UIImage imageNamed:@"icon_kjsy"];
    cell.conentLabel.text = @"GPOS智能总收益";
    
    // timeStampString 是服务器返回的13位时间戳
    NSString *timeStampString  = [self.modelArr[indexPath.row] time];
    
    // iOS 生成的时间戳是10位
    NSTimeInterval interval=[timeStampString doubleValue] / 1000.0;
    NSDate *date  = [NSDate dateWithTimeIntervalSince1970:interval];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateString    = [formatter stringFromDate: date];
    cell.ttimeLabel.text = dateString;
//    NSNumber * nsNumber1 = @([self.modelArr[indexPath.row] jia]);
    cell.shouyiLabel.text = [NSString stringWithFormat:@"+%@",@([self.modelArr[indexPath.row] jia].floatValue)];
    cell.shouyiLabel.textColor =  [UIColor colorWithRed:70/255.0f green:85/255.0f blue:254/255.0f alpha:1];
    
    return cell;
}

//上拉加载
-(void)loadMoreShopss{
    
    self.page++;
    __weak typeof(self) weakSelf = self;
//    weakSelf.modelArr = [[NSMutableArray alloc] init];
    int user = [[[NSUserDefaults standardUserDefaults] objectForKey:@"userId"] intValue];
    NSString * str = [weakSelf.timeStr stringByReplacingOccurrencesOfString:@"-"withString:@""];
    NSDictionary * params = @{@"startTime" : @([str intValue]),
                              @"pageSize" : @(10),
                              @"userId" : @(user),
                              @"page" : @(self.page)
                              };
    NSLog(@"oj---%@",params);
    [GPosAPI requestGetUserMinerDetailListWithParams:params andCallback:^(id obj) {
        NSLog(@"obj---%@",obj);
        if ( obj == nil ){
             [weakSelf.tableView.mj_footer endRefreshing];
            [SVProgressHUD showInfoWithStatus:@"请求失败"];
            [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
            [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
        }else {
            
            
            if ([[obj objectForKey:@"code"] intValue] == 200) {
                NSArray * arr = [[NSArray alloc] init];
                arr = [obj objectForKey:@"data"];
                for (NSDictionary * dic in arr) {
                    homeModel *model = [[homeModel alloc] init];
                    model.jia = [dic objectForKey:@"jia"];
                    model.tid = [dic objectForKey:@"id"];
                    model.time = [dic objectForKey:@"time"];
                    [weakSelf.modelArr addObject:model];
                }
                [weakSelf.tableView reloadData];
                [weakSelf.tableView.mj_footer endRefreshing];
                NSLog(@"self---%@",[obj objectForKey:@"data"]);
            }else if ([[obj objectForKey:@"code"] intValue] == 401 || [[obj objectForKey:@"code"] intValue] == 402) {
                
                UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"passWord"];
                //storyboard里的ID
                XMRegisterViewController *vc = [mainStory instantiateInitialViewController];
                vc.navigationController.navigationBarHidden=NO;
                //                    //设置当前窗口的根控制器
                
                [UIApplication sharedApplication].keyWindow.rootViewController=vc;
                [SVProgressHUD showInfoWithStatus:[obj objectForKey:@"message"]];
                [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
            }else {
                [SVProgressHUD showErrorWithStatus:[obj objectForKey:@"message"]];
                [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
                
            }
        }

    }];
    
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 73;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    homeModel * model = self.modelArr[indexPath.row];
    kjDetailsViewController * kjDetailsVC = [[kjDetailsViewController alloc] init];
    kjDetailsVC.tid = model.tid;
    kjDetailsVC.timeDate = model.time;
    [self.navigationController pushViewController:kjDetailsVC animated:YES];
    
}

//时间选择器
- (void)timeButtonAction:(UIButton *)sender {
    ITDatePickerController *datePickerController = [[ITDatePickerController alloc] init];
    //    datePickerController.tag = 100;                     // Tag, which may be used in
    datePickerController.delegate = self;               // Set the callback object
    datePickerController.showToday = NO;                // Whether to show "today",
    datePickerController.defaultDate = self.startDate;  // Default date
    //    datePickerController.maximumDate = self.endDate;    // maxinum date
    
    [self presentViewController:datePickerController animated:YES completion:nil];
    
}
- (void)datePickerController:(ITDatePickerController *)datePickerController didSelectedDate:(NSDate *)date dateString:(NSString *)dateString {
    
    //    NSInteger tag = datePickerController.tag;
    //    UIButton *button = [self.view viewWithTag:tag];
    NSString *strUrl = [dateString stringByReplacingOccurrencesOfString:@"." withString:@"-"];
    self.timeStr = strUrl;

    
    self.TimeLabel.text = @"";
    self.startDate = date;
    

    [self LoadData];
    NSLog(@"--%@",dateString);
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
